/*=============================================================================
Copyright (c) 2005 AUTOMATED LOGIC CORPORATION

This file is part of DominoTomcatSSOIntegration.
http://www.automatedlogic.com/domblog.nsf/dx/DominoTomcatSSOIntegration

DominoTomcatSSOIntegration is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

DominoTomcatSSOIntegration is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
http://www.gnu.org/licenses/gpl.html
=============================================================================*/

package com.automatedlogic.domino.sso;

import lotus.domino.NotesError;
import lotus.domino.NotesException;
import lotus.domino.NotesFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * Manages DIIOP connections with a Lotus Domino server.
 * Include the Lotus Domino file NCSO.jar in your classpath.
 *
 * @author Brian Green, Automated Logic Corporation
 * @version 2.4.3, Feb 25 2005
 * @since JDK1.4.2_06
 */
public class DominoBridge {

    /**
     * Session to the Domino server.  Use isDominoSessionAvailable() to see if the Session is available.
     * When you close the DIIOP connection to the Domino server, the dominoSession will not be available.
     * The Domino server will automatically close sessions after a preset time interval.  This is defined in the Domino Directory.
     */
    public lotus.domino.Session dominoSession;

    /**
     * If an error occurs, the error message text will be stored here.
     */
    public String dominoErrorText;

    /**
     * If an error occurs, the error id will be stored here.
     */
    public int dominoErrorID;


    /**
     * Open the DIIOP connection with the Domino server.  The session is opened using the LtpaToken cookie from the web browser.
     *
     * @param http         HttpServletRequest
     * @param dominoServer The host name and port address for connecting to the Domino server with DIIOP.
     *                     Example value: domino.acme.com:63148
     */
    public void openDominoSession(HttpServletRequest http, String dominoServer) {

        LtpaToken ltpaToken = new LtpaToken(http);

        try {
            //Open a session with the Domino server.  The Domino server must be running the DIIOP task, and must accept connections for the user.
            //Use the LtpaToken that is stored in the web browser (part of the HttpServletRequest).
            String token = ltpaToken.getTokenString();
            if (token != null) {
                dominoSession = NotesFactory.createSession(dominoServer, token);
            }
        } catch (NotesException e) {

            dominoErrorText = e.text;
            dominoErrorID = e.id;

            switch (dominoErrorID) {
                case NotesError.NOTES_ERR_SSOTOKEN_EXP:
                    //Single Sign-on Token has expired.
                    System.out.println("NotesException - " + dominoErrorID + " " + dominoErrorText);
                    break;
                case NotesError.NOTES_ERR_SERVER_ACCESS_DENIED:
                    //Access denied.
                    System.out.println("This user is not authorized to open DIIOP connections with the Domino server.  Check your DIIOP configuration.  NotesException - " + dominoErrorID + " " + dominoErrorText);
                    break;
                case NotesError.NOTES_ERR_GETIOR_FAILED:
                    //Could not get IOR from Domino Server.
                    System.out.println("Unable to open a DIIOP connection with " + dominoSession + ".  Make sure the DIIOP and HTTP tasks are running on the Domino server, and that ports are open.  NotesException - " + dominoErrorID + " " + dominoErrorText + ".");
                    break;
                default:
                    //Unexpected error.  Show detailed message.
                    System.out.println("NotesException - " + dominoErrorID + " " + dominoErrorText);
                    e.printStackTrace(System.out);
            }

        } catch (Exception e) {
            e.printStackTrace(System.out);
        }

    }


    /**
     * Open the DIIOP connection with the Domino server.  The session is opened with a username and password.
     *
     * @param dominoServer The host name and port address for connecting to the Domino server with DIIOP.
     *                     Example value: domino.acme.com:63148
     * @param username     Username from the login form.
     * @param password     Password from the login form.
     */
    public void openDominoSession(String dominoServer, String username, String password) {

        try {
            //Open a session with the Domino server.  The Domino server must be running the DIIOP task, and must accept connections for the user.
            dominoSession = NotesFactory.createSession(dominoServer, username, password);

        } catch (NotesException e) {

            dominoErrorText = e.text;
            dominoErrorID = e.id;

            switch (dominoErrorID) {
                case NotesError.NOTES_ERR_INVALID_USERNAME_PASSWD:
                    //Invalid password.
                    break;
                case NotesError.NOTES_ERR_INVALID_USERNAME:
                    //Invalid username.
                    break;
                case NotesError.NOTES_ERR_SERVER_ACCESS_DENIED:
                    //Access denied.
                    System.out.println("This user, " + username + ", is not authorized to open DIIOP connections with the Domino server.  Check your DIIOP configuration.  NotesException - " + dominoErrorID + " " + dominoErrorText);
                    break;
                case NotesError.NOTES_ERR_GETIOR_FAILED:
                    //Could not get IOR from Domino Server.
                    System.out.println("Unable to open a DIIOP connection with " + dominoSession + ".  Make sure the DIIOP and HTTP tasks are running on the Domino server, and that ports are open.  NotesException - " + dominoErrorID + " " + dominoErrorText + ".");
                    break;
                default:
                    //Unexpected error.  Show detailed message.
                    System.out.println("NotesException - " + dominoErrorID + " " + dominoErrorText);
                    e.printStackTrace(System.out);
            }

        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }


    /**
     * Close the DIIOP session with the Domino server.
     */
    public void closeDominoSession() {
        try {
            dominoSession.recycle();
        } catch (NotesException e) {
        }
    }


    /**
     * Determine if a session is available with the Domino server.
     *
     * @return True if the session is available, otherwise False.
     */
    public boolean isDominoSessionAvailable() {

        if (dominoSession == null) {
            return false;
        } else {
            if (dominoSession.isValid()) {
                return true;
            } else {
                return false;
            }
        }

    }


}
